package com.googlecode.tidej.client.util;

import java.io.IOException;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.tidej.client.Console;

public class HttpDataSource implements DataSource {
  String url;
  String user;
  String password;
  
  public HttpDataSource(String url) {
    this.url = url;
  }
  
  public void authenticate(String user, String password) {
    this.user = user;
    this.password = password;
  }
  
  private RequestBuilder newRequestBuilder(RequestBuilder.Method method) {
    RequestBuilder rb = new RequestBuilder(method, GWT.getModuleBaseURL() + "proxy");
    String requestUrl = url;
    if (user != null && !user.isEmpty()) {
      rb.setHeader("Authorization", "Basic " + Base64.encode(user + ":" + password));
    }
    Console.log("request url: " + requestUrl);
    
    rb.setHeader("X-Forward-To", requestUrl);
    return rb;
  }
  
  
  public void getContent(final AsyncCallback<String> callback) {
    //Window.alert("loading: " + fileName);
    RequestBuilder rb = newRequestBuilder(RequestBuilder.GET);
    rb.setCallback(new RequestCallback() {
      @Override
      public void onResponseReceived(Request request, Response response) {
        Console.log("OnResponseReceived");
        if (response.getStatusCode() == 200) {
          callback.onSuccess(response.getText());
        } else {
          Console.log("getContent failed: " + response.getStatusCode() + ": " + response.getStatusText());
          callback.onFailure(new IOException(response.getStatusCode() + ": " + response.getStatusText()));
        }
        
      }

      @Override
      public void onError(Request request, Throwable exception) {
        Console.log("Onerror");
        callback.onFailure(exception);
      }
    });
    try {
      rb.send();
    } catch (RequestException e) {
      callback.onFailure(e);
    }
  }

  @Override
  public void setContent(String content, final AsyncCallback<Void> callback) {
    RequestBuilder rb = newRequestBuilder(RequestBuilder.PUT);
    rb.setRequestData(content);
    rb.setCallback(new RequestCallback() {
      @Override
      public void onResponseReceived(Request request, Response response) {
        Console.log("response: " + response.getStatusCode() + ": " + response.getStatusText());
        callback.onSuccess(null);
      }

      @Override
      public void onError(Request request, Throwable exception) {
        Console.log("error: " + exception);
        callback.onFailure(exception);
      }
    });
    try {
      rb.send();
    } catch (RequestException e) {
      callback.onFailure(e);
    }
  }
  
}
